#pragma once
#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
class TCPServer;
struct ThreadData
{
    ThreadData(TCPServer* self, int sockfd) : _self(self) , _sockfd(sockfd)
    {}


    TCPServer* _self;
    int _sockfd;
};
class TCPServer
{
public:
    TCPServer(uint16_t port) // 通过端口号构造一个TCPServer对象
        : _port(port), _isrunning(false)
    {
    }
    void BindSocket()
    {
        sockaddr_in addr;
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);
        int n = bind(_listensock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
        if (n < 0)
        {
            std::cerr << "Server Bind Error!" << std::endl;
            exit(2);
        }
    }
    void CreateSocket()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            std::cerr << "create socket error!\n"
                      << std::endl;
            exit(1);
        }
    }
    void SetListenSocket()
    {
        int n = listen(_listensock, 8);
        if (n < 0)
        {
            std::cerr << "Set Listen Status Error!" << std::endl;
            exit(3);
        }
    }
    void InitServer() // 初始化TCPServer
    {
        // 1、创建套接字
        CreateSocket();
        // 2、绑定套接字
        BindSocket();
        // 3、设置套接字为listen状态
        SetListenSocket();
    }

    void Accept(int &sockfd) // 服务器提供服务之前
    {
        // 1、接受客户端的连接请求
        sockaddr_in peer;
        socklen_t len;
        sockfd = accept(_listensock, reinterpret_cast<sockaddr *>(&peer), &len);
        if (sockfd < 0)
        {
            std::cerr << "accept client link error!" << std::endl;
            exit(4);
        }
    }
    void Service(int sockfd)
    {
        while (true)
        {
            char buffer[1024];
            int n = recv(sockfd, buffer, sizeof(buffer), MSG_WAITALL);
            if (n > 0)
            {
                // 接收成功
                std::cout << "Client say# " << buffer << std::endl;
                // 服务器把buffer中的数据重新发送给客户端，完成服务
                send(sockfd, buffer, sizeof(buffer), 0);
            }
            else if (n == 0)
            {
                // 客户端套接字关闭
                std::cout << "client socket close!" << std::endl;
                close(sockfd);
                exit(0);
            }
            else
            {
                // recv error
                std::cerr << "recv error!" << std::endl;
                close(sockfd);
                exit(5);
            }
        }
    }
    static void* threadroutine(void* arg)
    {
        pthread_detach(pthread_self());
        ThreadData* self = reinterpret_cast<ThreadData*>(arg);
        //提供服务
        self->_self-> Service(self->_sockfd);
        delete self;
    }
    void Loop() // 提供echo服务
    {
        // 服务器需要不断获取连接
        _isrunning = true;
        while (_isrunning)
        {
            int sockfd = -1;
            Accept(sockfd);
            pthread_t tid;
            ThreadData* data = new ThreadData(this,sockfd);
            pthread_create(&tid , nullptr , threadroutine , data);
        }
        _isrunning = false;
    }

protected:
    uint16_t _port; // 端口号
    int _listensock;
    bool _isrunning; // 控制Server是否运行
};